import util from '../../utils/util'
const db = wx.cloud.database({
    env: 'work1-0g1b3grp436e9236'
})
const dayjs = require('../../miniprogram_npm/miniprogram_npm/dayjs/index')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLike: false,
        // 曾经是否收藏过
        isRecentLike: false,
        isSendCv: false,
        loading: true,
        showBottm: true,
        // 确认投递
        sendcvActions: [{name: '确认投递', color: '#ee0a24', value: 0}, {name: '暂时放弃'}],
        showSendcvAction: false,
        showContactor: true
    },

    // 发送私信
    toPrivateChat(e) {
        const userInfo = wx.getStorageSync('userInfo')
        if (!userInfo) {
          util.myToastNone('请先登录～')
            return
        }
        const toOpenId = e.currentTarget.dataset.id
        // console.log(toOpenId)
        if (toOpenId === userInfo.userOpenId) {
            util.myToastError('不能发给自己～')
            return
        }
        wx.navigateTo({
          url: '/pages/privateChat/privateChat?to=' + toOpenId,
        })
    },

    // 确认弹出框
    onCloseSendcvActionSheet() {
        this.setData({showSendcvAction: false})
    },

    onSelectSendcvActionSheet({detail}) {
        if (detail.value === 0) {
            const userInfo = wx.getStorageSync('userInfo')
            db.collection('work_post').add({
                data: {
                    cvId: this.data.cvId,
                    jobId: this.data.jobId,
                    status: 0,
                    realName: this.data.realName,
                    gender: this.data.gender,
                    age: this.data.age,
                    workExp: this.data.workExp,
                    avatar: userInfo.avatarUrl,
                    updateTime: new Date(),
                    jobName: this.data.jobName,
                    salary: this.data.salary,
                    content: this.data.content,
                    location: this.data.location,
                    companyImg: this.data.companyImg,
                    companyName: this.data.companyName,
                    userId: userInfo.userId,
                    userOpenId: userInfo.userOpenId
                }
            }).then(res=>{
                // 投递成功
                const _ = db.command
                db.collection('work_job').doc(this.data.jobId).update({
                    data: {
                        // 表示指示数据库将字段自增 1
                        postNum: _.inc(1)
                    },
                })
                // 记录修改过程
                db.collection('work_cv_status_record').add({
                    data: {
                        postId: res._id,
                        status: 0,
                        updateTime: new Date()
                    }
                })
                this.setData({isSendCv: true})
                util.myToastSuccess('投递成功')
            })
        }
        this.setData({showSendcvAction: false})
    },

    // 查看公司详情
    toFirmPage() {
        // 防止递归
        if (!this.data.showContactor) {
            wx.navigateBack({
              delta: 1,
            })
            return
        }
        wx.navigateTo({
          url: '/pages/firm/firm?id=' + this.data.firmId
        })
    },

    // 投递简历
    async sendCv() {
      const userInfo = wx.getStorageSync('userInfo')
      if (!userInfo) {
        util.myToastNone('请先登录～')
        return
      }
      if (!this.data.jobId) return
      const res1 = await db.collection('work_cv').where({userId: userInfo.userId}).get()
      // 用户没有制作过简历
      if (res1.data.length === 0) {
        util.myToastNone('请制作简历后重试')
        return
      }
      this.setData({
        showSendcvAction: true, 
        realName: res1.data[0].realName,
        gender: res1.data[0].gender,
        age: res1.data[0].age,
        workExp: res1.data[0].workExp
      })
    },

    // 判断是否已经投递简历
    async judgeIsSendCv() {
      const userInfo = wx.getStorageSync('userInfo')
      if (!userInfo) return
      const result = await (await db.collection('work_cv').where({userId: userInfo.userId}).get())
      // 用户没有制作过简历
      if (result.data.length === 0) {
          return
      }
      this.setData({cvId: result.data[0]._id})
      db.collection('work_post').where({jobId: this.data.jobId, cvId: this.data.cvId}).get().then(res=>{
        if (res.data.length !== 0) {
          this.setData({isSendCv: true})
        }
      })
    },

    // 加载信息
    getJobInfo(jobId) {
        db.collection('work_job').doc(jobId).get().then(res=>{
          // console.log(res.data)
          this.setData(res.data)
          this.setData({
              updateTime: dayjs(res.data.updateTime).format("YYYY-MM-DD HH:mm"),
              endTime: dayjs(res.data.endTime).format("YYYY-MM-DD"),
              beginTime: dayjs(res.data.beginTime).format("YYYY-MM-DD"),
              continueTime: res.data.continueTime,
              address: res.data.jobAddress,
          })
          db.collection('work_company').where({userId: res.data.userId}).get().then(res=>{
              // console.log(res.data[0])
              this.setData({
                  firmId: res.data[0]._id,
                  companyName: res.data[0].companyName,
                  companyImg: res.data[0].companyImg
              })
          })
          db.collection('work_user').doc(res.data.userId).get().then(res=>{
              // console.log(res.data)
              this.setData({
                  avatar: res.data.avatar,
                  nickName: res.data.nickName,
                  userOpenId: res.data.openid,
                  loading: false
              })
          })
      })
    },

    // 判断是否已经收藏
    judgeIsCollected() {
        const userInfo = wx.getStorageSync('userInfo')
        if (!userInfo) {
          return
        }
        const params = {
          userId: userInfo.userId,
          jobId: this.data.jobId
        }
        db.collection('work_collect_job').where(params).get().then(res=>{
          if (res.data.length !== 0 && res.data[0].status === 1) {
            this.setData({isLike: true})
          } else if (res.data.length !== 0 && res.data[0].status === 0) {
            this.setData({isRecentLike: true})
          }
        })
    },

    // 收藏
    async collectJob() {
        const userInfo = wx.getStorageSync('userInfo')
        if (!userInfo) {
          util.myToastNone('请先登录～')
          return
        }
        util.myLoading()
        if (this.data.isLike) {
          // 取消收藏
          await db.collection('work_collect_job').where({userId: userInfo.userId, jobId: this.data.jobId,}).update({
            data: {
              status: 0,
              updateTime: new Date()
            }
          }).then(res=>{
            // console.log('取消收藏', res)
            util.myToastNone('已取消')
          })
        } else {
          // 曾经是否收藏
          if (this.data.isRecentLike) {
            await db.collection('work_collect_job').where({userId: userInfo.userId, jobId: this.data.jobId}).update({
              data: {
                status: 1,
                updateTime: new Date()
              }
            }).then(res=>{
              // console.log('收藏成功', res)
              util.myToastNone('收藏成功')
            })
          } else {
            const params = {
              userId: userInfo.userId,
              jobId: this.data.jobId,
              status: 1,
              updateTime: new Date(),
              avatar: this.data.avatar,
              content: this.data.content,
              jobName: this.data.jobName,
              location: this.data.location,
              nickName: this.data.nickName,
              salary: this.data.salary
            }
            // console.log(params)
            await db.collection('work_collect_job').add({
              data: params
            }).then(res=>{
              // console.log('收藏成功', res)
              util.myToastNone('收藏成功')
            })
          }
        }
        this.setData({
          isLike: !this.data.isLike
        })
        this.judgeIsCollected()
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // console.log(options)
        if (options.fromFirmPage === '1') {
            this.setData({showContactor: false})
        }
        this.setData({jobId: options.id})
        this.judgeIsSendCv()
        this.judgeIsCollected()
        util.myLoading()
        this.getJobInfo(options.id)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})